package be.pluyckx.batteryprogress.data;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Philip on 13/09/13.
 * <p/>
 * An class that implements the Observable interface. This list stores observers in a list. Look also
 * at the class comments of {@link be.pluyckx.batteryprogress.data.Observable}.
 */
public class ObservableListImpl implements Observable {
  private List<Observer> mObservers;

  public ObservableListImpl() {
    mObservers = new LinkedList<Observer>();
  }

  @Override
  public boolean addObserver(Observer observer) {
    return mObservers.add(observer);
  }

  @Override
  public boolean removeObserver(Observer observer) {
    Iterator<Observer> iterator = mObservers.iterator();

    while (iterator.hasNext()) {
      Observer o = iterator.next();
      if (o.equals(observer)) {
        iterator.remove();
        return true;
      }
    }

    return false;
  }

  @Override
  public boolean isObserving(Observer observer) {
    Iterator<Observer> iterator = mObservers.iterator();

    while (iterator.hasNext()) {
      Observer o = iterator.next();
      if (o.equals(observer)) {
        return true;
      }
    }

    return false;
  }

  protected void fireDataChanged(Object observable, Observer.ChangeInfo info) {
    for (Observer o : mObservers) {
      o.onDataChanged(observable, info);
    }
  }
}
